package com.bwpm.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.bwpm.config.BwpmConfig;
import com.bwpm.model.NjamsTMonitorAttributes;
import com.bwpm.model.NjamsTMonitorEvents;
import com.bwpm.model.NjamsTMonitorMain;
import com.bwpm.plugin.PageJ;
import com.jfinal.plugin.activerecord.Page;

public class QueryMainInfomationService {

	public static  Logger log = LogManager.getLogger(Class.class.getName());
	
	/**
	 * get Main process entry
	 * @param m
	 * @return
	 */
	public PageJ<NjamsTMonitorMain> queryMainInfo(Map<String, String> m) {
		StringBuffer sqlb = new StringBuffer();
		sqlb.append("select  m1.*  from (SELECT DO.OBJECTLEVEL OBJECTLEVEL, DO.OBJECTNAME PROCESSNAME, LOGID, CORRELATIONLOGID, PARENTLOGID, EXTERNALLOGID, MACHINENAME, BUSINESSSERVICE, BUSINESSOBJECT, BUSINESSSTART, BUSINESSEND, JOBSTART, CUSTOMID, STATUS, DURATION_MS,DOMAIN_OBJECT_ID FROM NJAMS_T_MONITOR_MAIN m inner join NJAMS_V_DOMAIN_OBJECTS_LEVEL DO  " +
				"ON DOMAIN_OBJECT_ID = DO.OBJ_ID " +
				"  AND m.jobstart between NEW_TIME(to_date(?, 'YYYY-MM-DD HH24:MI:SS'), 'GMT', 'PST') AND NEW_TIME(to_date(?, 'YYYY-MM-DD HH24:MI:SS'), 'GMT', 'PST')  AND  DO.OBJECTLEVEL = 1 ");

		/*
		 * required datetime 
		 */
		String datetime_start;
		if(m.get("datetime_start")!=null &&  !"".equals(m.get("datetime_start"))){
			datetime_start = m.get("datetime_start")+":00";
		}else{
			datetime_start=getDefaultDatetime()[0];
		}
		String datetime_end;
		if(m.get("datetime_end")!=null && !"".equals(m.get("datetime_end"))){
			datetime_end = m.get("datetime_end")+":59";
		}else{
			datetime_end=getDefaultDatetime()[1];
		}
		Object[] ob = new Object[]{datetime_start,datetime_end};
		String funcno = "";
		if(m.get("funcno") != null && !"".equals(m.get("funcno"))){
			sqlb.append(" AND BUSINESSSERVICE =  ?  ");
			funcno = m.get("funcno")+BwpmConfig.getP().get("funcnosuffix").trim();
			ob = new  Object[]{datetime_start,datetime_end,funcno};
		}
		
//		if(m.get("customno") != null && !"".equals(m.get("customno"))){
//			sqlb.append("");
//			String customno = m.get("customno");
//		    paramList.add(customno);
//		    ob = new  Object[]{datetime_start,datetime_end,funcno,m.get("customno")};
//		}
		
		sqlb.append(") m1 order by m1.JOBSTART desc");
		
		String sql = sqlb.toString();
		log.info(sql);
		Page<NjamsTMonitorMain> pt = NjamsTMonitorMain.dao.paginate(
				Integer.parseInt(m.get("page")),
				Integer.parseInt(m.get("rows")), sql, ob);
		//for Easyui packaging the Page<> object
		return new PageJ<NjamsTMonitorMain>(pt.getList(),pt.getPageNumber(),pt.getPageSize(), pt.getTotalPage(),pt.getTotalRow());
		
		
	}
	
	/**
	 * it's a tool function
	 * get Start and End datetime
	 * @return
	 */
	private static String[] getDefaultDatetime(){
		SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date currentTime = new Date();
		String dateString1 = formatter1.format(currentTime)+" 00:00:00";
		String dateString2 = formatter2.format(currentTime);
		return new String[]{dateString1,dateString2};
		}

	/**
	 * get event of main process detail 
	 * @param map
	 * @return
	 */
	public List<NjamsTMonitorEvents> queryMonitorEvents(Map<String, String> map) {
				String sql = "SELECT e.* "
				+ " FROM NJAMS_T_MONITOR_EVENTS e "
				+ " WHERE e.main_logid = ? "
				+ " order by e.EVENTDATETIME asc,e.SEQUENCE_NUMBER";
		log.info(sql);
		return NjamsTMonitorEvents.dao.find(sql, map.get("main_logid"));
	}

	/**
	 * get main process detail
	 * @param map
	 * @return
	 */
	public List<NjamsTMonitorMain> queryCorrelationLog(Map<String, String> map) {
		String sql = "select  m1.* from (SELECT "+
	"DO.OBJECTLEVEL OBJECTLEVEL,DO.OBJECTNAME PROCESSNAME,LOGID,CORRELATIONLOGID,PARENTLOGID,EXTERNALLOGID,MACHINENAME,BUSINESSSERVICE,BUSINESSOBJECT,BUSINESSSTART,BUSINESSEND,JOBSTART,CUSTOMID,STATUS,DURATION_MS,DOMAIN_OBJECT_ID"+
	" FROM NJAMS_T_MONITOR_MAIN m inner join NJAMS_V_DOMAIN_OBJECTS_LEVEL DO "+
	" ON m.CORRELATIONLOGID = ? AND DOMAIN_OBJECT_ID = DO.OBJ_ID) m1 order by m1.OBJECTLEVEL asc";
		log.info(sql);
		return NjamsTMonitorMain.dao.find(sql, map.get("CORRELATIONLOGID"));
	}

	/**
	 * get process record attribute
	 * @param map
	 * @return
	 */
	public List<NjamsTMonitorAttributes> queryAttribute(Map<String, String> map) {
		String sql = "select unique a.main_logid,a.attribute_name, a.attribute_value from njams_t_monitor_attributes a "
				+ " where a.main_logid = ? "
				+ " and a.attribute_name in ('FunctionNo','CustNo','TrackingID') order by a.attribute_name";
		log.info(sql);
		return NjamsTMonitorAttributes.dao.find(sql, map.get("main_logid"));
	}
	
}
